package LeetCode;

//
// Created by ✎﹏ℳ๓独赏☆独醉 on 2024/5/22.
//
//https://leetcode.cn/problems/add-binary/description/
public class 二进制求和 {
    public static void main(String[] args) {
        String a = "1";
        String b = "111";
        System.out.println(addBinary(a,b));
    }

    private static String addBinary(String a, String b) {
        StringBuilder sb1;
        StringBuilder sb2;
        if(a.length() > b.length()){
            sb1 = new StringBuilder(a);
            sb2 = new StringBuilder(b);
        }else {
            sb1 = new StringBuilder(b);
            sb2 = new StringBuilder(a);
        }

        int left = sb1.length()-1,right = sb2.length()-1;
        while (left >= 0 && right >= 0){
            sb1.setCharAt(left, (char)(sb1.charAt(left) + Character.getNumericValue(sb2.charAt(right))));
            left--;
            right--;
        }
        System.out.println(sb1);
        int point = sb1.length() - 1;
        while (point > 0){
            if(sb1.charAt(point) >= '2'){
                sb1.setCharAt(point, (char) (sb1.charAt(point) - 2));
                sb1.setCharAt(point-1, (char) (sb1.charAt(point-1) + 1));
            }
            point--;
        }
        System.out.println(sb1);
        StringBuilder res;
        if(sb1.charAt(0) >= '2'){
            sb1.setCharAt(0, (char) (sb1.charAt(0) - 2));
            res = new StringBuilder("1");
            res.append(sb1);
        }else {
            res = sb1;
        }
        return res.toString();
    }


//    public static String addBinary(String a, String b) {
//        int num1 = binaryToInteger(a);
//        int num2 = binaryToInteger(b);
//        System.out.println(num1 + " " + num2);
//        int res = num1 + num2;
//        return Integer.toBinaryString(res);
//    }
//
//    private static int binaryToInteger(String str) {
//        int num = 0,flag = 0;
//        for (int i = str.length()-1; i >= 0; i--) {
//            num += Character.getNumericValue(str.charAt(i)) * Math.pow(2.0,flag++);
//        }
//        return num;
//    }
}
